import collections


class Solution:
    def numSubarraysWithSum(self, A: list, S: int) -> int:
        counter = collections.Counter()
        res = 0
        cur_sum = 0
        for i in range(len(A)):
            cur_sum += A[i]
            if cur_sum == S:
                res += 1
            diff = cur_sum - S
            res += counter[diff]

            counter[cur_sum] += 1

        return res
